package com.lunz.securityproject.conf.handle;

import com.alibaba.fastjson.JSON;
import com.lunz.securityproject.module.JsonResult;
import com.lunz.securityproject.module.ResultCode;
import com.lunz.securityproject.module.ResultTool;
import com.lunz.securityproject.util.VaptchaUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 施瑞贤
 * @email shiruixian@zhongruigroup.com
 * @date 2021/10/29 9:22
 */
public class VaptchaFilterr extends OncePerRequestFilter {

    /**
     * 需要vaptcha验证的接口
     */
    private String[] urls = new String[]{"/login", "/user/register", "/user/updatePassword" ,"/user/deleteUser"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断请求接口是否是需要验证的接口
        boolean b = false;
        String url = request.getRequestURI();
        for (String u : urls) {
            if(u.equals(url)){
                b = true;
            }
        }
        if(b){
            //判断是否为post，不允许非post请求
            if(!"POST".equals(request.getMethod())){
                throw new AuthenticationServiceException("不支持该请求类型: " + request.getMethod());
            }

            String token = request.getParameter("token");
            String server = request.getParameter("server");

            //token与server值为空
            if(token == null || token.length() <= 0 || "".equals(token)){
                failResult(response, ResultCode.VAPTCHA_TOKEN_NULL);
                return;
            }
            if(server == null || server.length() <= 0 || "".equals(server)){
                failResult(response, ResultCode.VAPTCHA_SERVER_NULL);
                return;
            }

            //验证失败
            try {
                int result = VaptchaUtil.postJSON(server, token);
                if(result != 1){
                    failResult(response, ResultCode.VAPTCHA_CHECK_FAIL);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //如果token、server值不为空，且验证成功，则进行下一个过滤器
        filterChain.doFilter(request, response);
    }

    //返回错误信息
    private void failResult(HttpServletResponse response, ResultCode rc){
        //返回json数据
        JsonResult jsonResult = ResultTool.fail(rc);
        //处理编码方式，防止中文乱码的情况
        response.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        try {
            response.getWriter().write(JSON.toJSONString(jsonResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
